// canvas 全局配置
import {uploadFile,downFile} from '../../utils/config'
var context:any = null;
var isButtonDown = false;
var arrx:any = [];
var arry:any = [];
var arrz:any = [];
var canvasw = 0;
var canvash = 0;
//注册页面
Page({
  canvasIdErrorCallback: function (e:any) {
    console.error(e.detail.errMsg)
  },
  //开始
  canvasStart: function (event:any) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
 
  },
  data: {
    bf:'wname'
  },
 
  onLoad: function (options:any) {
    var that = this
    if(options.bf){
      
      that.setData({
        bf:options.bf
      })
    }
    // 使用 wx.createContext 获取绘图上下文 context
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');

    context.draw();
  },


 
  //过程
  canvasMove: function (event:any) {
  
    if (isButtonDown) {
      arrz.push(1);
     // console.log(event)
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    };
 
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      };
 
    };
    context.clearRect(0, 0, canvasw, canvash);
    context.setStrokeStyle('#000000');
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
 
    context.draw(false);
  },
  // 点击保存图片
  clickMe: function () {
    var that = this
    let pages = getCurrentPages(),// 获取页面栈
    prevpage= pages[pages.length - 2];// 上一个页面
    wx.canvasToTempFilePath({
      canvasId: 'canvas',
      fileType: 'png', 
      success: function (res) {
        uploadFile(res.tempFilePath,(r:any)=>{
          console.log(r.data.id)
          let it={url:res.tempFilePath,id:r.data.id}
          prevpage.setData({
            [that.data.bf]:it
          })
          that.cleardraw()
          wx.navigateBack();
        })



        
      }
    })
  },
  canvasEnd: function (event:any) {
    isButtonDown = false;
  },
  cleardraw: function () {
    //清除画布
    arrx = [];
    arry = [];
    arrz = [];
    context.draw(false);
  },
 
})